package org.jivesoftware.openfire.chatlogs;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;






import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.chatlogs.ChatLogs.ChatLogsConstants;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;


public class ChatLogsPlugin implements PacketInterceptor, Plugin {
	
	private static final Logger log = LoggerFactory.getLogger(ChatLogsPlugin.class);
	 private static PluginManager pluginManager;
     private static DbChatLogsManager logsManager;
     private InterceptorManager interceptorManager;
     public ChatLogsPlugin() {
         interceptorManager = InterceptorManager.getInstance();
         logsManager = DbChatLogsManager.getInstance();
     }
     @Override
 	public void interceptPacket(Packet packet, Session session,
 			boolean incoming, boolean processed) throws PacketRejectedException {
 		// TODO Auto-generated method stub
    	 if (session != null) {
             debug(packet, incoming, processed, session);
         }
         
         JID recipient = packet.getTo();
         if (recipient != null) {
             String username = recipient.getNode();
             if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
                 return;
             } else if (!XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals(recipient.getDomain())) {
                 return;
             } else if ("".equals(recipient.getResource())) {
             }
         }
         this.doAction(packet, incoming, processed, session);

 	}
     
	
	private void doAction(Packet packet, boolean incoming, boolean processed,
			Session session) {
		// TODO Auto-generated method stub
		  Packet copyPacket = packet.createCopy();
		  if (packet instanceof Message) {		
	             Message message = (Message) copyPacket;
	             if(message.getType()==Message.Type.chat){//single
//	            	 debug("single chat"+message.toXML());
	             }
	         
                 if (processed || !incoming) {
                     return;
                 }
                 int adds = 1;
                 logsManager.add(get(adds,packet, incoming, session));
                 adds = 2;	
                 logsManager.add(get(adds,packet, incoming, session));
		  }
	}
	
	private ChatLogs get(int adds,Packet packet, boolean incoming, Session session) {
		// TODO Auto-generated method stub
		   Message message = (Message) packet;
	         ChatLogs logs = new ChatLogs();
	         JID jid = session.getAddress();
	         if (incoming) {       
	             logs.setSender(jid.getNode());
	             JID recipient = message.getTo();
	             logs.setReceiver(recipient.getNode());
	             if(adds==1){
	             //msgUser= receiver
	             logs.setMsgUser(recipient.getNode());
	             }
	             else if(adds==2){
	            	 //msgUser = sender
		             logs.setMsgUser(jid.getNode());

	             }
	         } 
	       
	         logs.setContent(message.getBody());
	         SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
	         String CreateDate= df.format(new Date());
	         logs.setCreateDate(CreateDate);
	         logs.setDetail(message.toXML());
	         logs.setLength(logs.getContent().length());
	         logs.setSessionJID(jid.toString());
	         long messageID = SequenceManager.nextID(ChatLogsConstants.CHAT_LOGS);
	         logs.setMessageId(messageID);	
	       
	         return logs;
	}
	private void debug(Packet packet, boolean incoming, boolean processed,
			Session session) {
		// TODO Auto-generated method stub
		  String info = "[ packetID: " + packet.getID() + ", to: " + packet.getTo() + ", from: " + packet.getFrom() + ", incoming: " + incoming + ", processed: " + processed + " ]";
	         long timed = System.currentTimeMillis();
	         debug("---------------------------- start ----------------------------" + timed);
	         debug("id:" + session.getStreamID() + ", address: " + session.getAddress());
	         debug("info: " + info);
	         debug("xml: " + packet.toXML());
	         debug("------------------------------ end ------------------------------" + timed);
	         
	         log.info("id:" + session.getStreamID() + ", address: " + session.getAddress());
	         log.info("info: {}", info);
	         log.info("plugin Name: " + pluginManager.getName(this) + ", xml: " + packet.toXML());

	}
	private void debug(Object message) {
        if (true) {

        	log.debug("debug", message);
        	
        }
    }

	@Override
	public void initializePlugin(PluginManager manager, File pluginDirectory) {
		// TODO Auto-generated method stub
		 interceptorManager.addInterceptor(this);
         pluginManager = manager;
         debug("chatlogs plugin init success");

	}

	@Override
	public void destroyPlugin() {
		// TODO Auto-generated method stub
		interceptorManager.removeInterceptor(this);
        debug("chatlogs plugin destroy success");

	}

	

}
